package com.jsh.erp.utils;

public class NumberToWords {
    private static final String[] ONES = {
            "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
            "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"
    };

    private static final String[] TENS = {
            "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"
    };

    private static final String[] THOUSANDS = {
            "", "Thousand", "Million", "Billion"
    };

    public static String convertToWords(float number) {
        if (number == 0) {
            return "Zero";
        }

        long dollars = (long) number;
        int cents = (int) ((number - dollars) * 100);

        String result = convertWholeNumber(dollars);

        if (cents > 0) {
            result += " and " + convertWholeNumber(cents) + " Cent" + (cents == 1 ? "" : "s");
        }

        return result;
    }

    private static String convertWholeNumber(long number) {
        String word = "";
        int index = 0;

        do {
            int n = (int) (number % 1000);
            if (n != 0) {
                String s = convertLessThanOneThousand(n);
                word = s + " " + THOUSANDS[index] + " " + word;
            }
            index++;
            number /= 1000;
        } while (number > 0);

        return word.trim();
    }

    private static String convertLessThanOneThousand(int number) {
        String word;

        if (number % 100 < 20) {
            word = ONES[number % 100];
            number /= 100;
        } else {
            word = ONES[number % 10];
            number /= 10;

            word = TENS[number % 10] + " " + word;
            number /= 10;
        }

        if (number == 0) return word;
        return ONES[number] + " Hundred " + word;
    }

    public static void main(String[] args) {
        System.out.println(convertToWords(1234.56f));
        System.out.println(convertToWords(65584.03f));
    }
}
